package vn.smartoffice.promail.controller.dialog;

import org.springframework.dao.DuplicateKeyException;
import org.zkoss.bind.BindUtils;
import org.zkoss.bind.annotation.AfterCompose;
import org.zkoss.bind.annotation.Command;
import org.zkoss.bind.annotation.ContextParam;
import org.zkoss.bind.annotation.ContextType;
import org.zkoss.bind.annotation.ExecutionArgParam;
import org.zkoss.util.resource.Labels;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.select.Selectors;
import org.zkoss.zk.ui.select.annotation.VariableResolver;
import org.zkoss.zk.ui.select.annotation.Wire;
import org.zkoss.zk.ui.select.annotation.WireVariable;
import org.zkoss.zkplus.spring.DelegatingVariableResolver;
import org.zkoss.zul.Messagebox;
import org.zkoss.zul.Window;

import vn.smartoffice.auth.UserService;
import vn.smartoffice.promail.dto.MailFolderNode;
import vn.smartoffice.promail.entity.MailFolder;
import vn.smartoffice.promail.services.MailFolderService;

@VariableResolver(DelegatingVariableResolver.class)
public class FolderDialogCtr {

	@WireVariable
	private MailFolderService mailFolderService;
	@WireVariable
	private UserService userService;

	private MailFolderNode node;
	private MailFolder chidlFolder;
	private boolean isCreateFolder;

	public MailFolderNode getNode() {
		if (isCreateFolder) {
			return new MailFolderNode(chidlFolder);
		} else {
			return node;
		}
	}

	@Wire
	private Window folderDialog;

	@AfterCompose
	public void afterCompose(@ContextParam(ContextType.VIEW) Component view,
			@ExecutionArgParam("node") MailFolderNode node, @ExecutionArgParam("isCreateFolder") boolean isCreateFolder) {
		Selectors.wireComponents(view, this, false);
		this.node = node;
		this.isCreateFolder = isCreateFolder;
		if (isCreateFolder) {
			chidlFolder = new MailFolder();
		}
	}

	@Command("save")
	public void save() {
		try {
			chidlFolder.setUser(userService.getCurrentUser());
			chidlFolder.setOpen(false);
			chidlFolder.setParentId(node.getId());
			node.getData().setOpen(true);
			mailFolderService.update(node.getData());
			mailFolderService.save(chidlFolder);
			folderDialog.detach();
			BindUtils.postGlobalCommand(null, null, "refreshMailFolder", null);
		} catch (Exception ex) {
			if (ex instanceof DuplicateKeyException) {
				Messagebox.show(Labels.getLabel("folder.nameExits.errorMessages"), Labels.getLabel("wraning.title"), Messagebox.OK, Messagebox.EXCLAMATION);
			} else {
				throw ex;
			}
		}
	}

	@Command("update")
	public void update() {
		mailFolderService.update(node.getData());
		folderDialog.detach();
		BindUtils.postGlobalCommand(null, null, "refreshMailFolder", null);
	}

	@Command("cancel")
	public void cancel() {
		folderDialog.detach();
	}

	@Command("controlSaveOrCancel")
	public void controlSaveOrCancel() {
		if (isCreateFolder) {
			save();
		} else {
			update();
		}
	}
}
